//
//  WYJStatusTableViewCell.swift
//  MySinaWeibo
//
//  Created by eastriver on 16/10/15.
//  Copyright © 2016年 believewilliam. All rights reserved.
//

import UIKit
import SDWebImage
let commonMargin: CGFloat = 8
private let pictureItemMargin: CGFloat = 3
private let maxWidth = screenWidth - 2 * commonMargin
private let itemWidth =  (maxWidth - 2 * pictureItemMargin) / 3
let collectionViewCellID = "WYJPictureCollectionViewCell"

class WYJStatusTableViewCell: UITableViewCell {
    
    @IBOutlet weak var iconImgV: UIImageView!

    @IBOutlet weak var nameLab: UILabel!
    @IBOutlet weak var memberImgV: UIImageView!
    @IBOutlet weak var timeLab: UILabel!
    @IBOutlet weak var sourceLab: UILabel!
    
    @IBOutlet weak var contentLab: UILabel!
    
    @IBOutlet weak var avatarImgV: UIImageView!
    
    @IBOutlet weak var pictureCollectionView: WYJPictureCollectionView!
    
    @IBOutlet weak var pictureViewWidth: NSLayoutConstraint!
    
    @IBOutlet weak var pictureViewHeight: NSLayoutConstraint!
    
    @IBOutlet weak var pictureViewFlowLayout: UICollectionViewFlowLayout!
    
    @IBOutlet weak var pictureViewTopConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var toolBar: UIView!
    
    @IBOutlet weak var commenBtn: UIButton!
    
    @IBOutlet weak var repostBtn: UIButton!
    
    @IBOutlet weak var ohYeahBtn: UIButton!
    
    @IBOutlet weak var retweetedContentLab: UILabel!
    /*
    // 配图的数据源
    var pic_urls: [WYJStatusPictureModel]? {
        didSet {
            pictureCollectionView.testLab.text = "\(pic_urls?.count ?? 0)张"
            pictureCollectionView.reloadData() // 不明白此处为何要刷新数据，但是如果不写此行代码，确实图片显示错乱了
        }
    }
 */
    // 视图模型属性
    var statusViewModel: WYJStatusViewModel? {
        didSet{
            timeLab.text = statusViewModel?.time_text
            sourceLab.text = statusViewModel?.source_text
            contentLab.text = statusViewModel?.statusModel?.text
            avatarImgV.image = statusViewModel?.avatarImg
            memberImgV.image = statusViewModel?.memberImg
            nameLab.text = statusViewModel?.statusModel?.user?.name
            iconImgV.sd_setImage(with: statusViewModel?.iconURL)
            // 设置工具栏文字
            repostBtn.setTitle(statusViewModel?.reposts_text, for: .normal)
            commenBtn.setTitle(statusViewModel?.comments_text, for: .normal)
            ohYeahBtn.setTitle(statusViewModel?.ohYeah_text, for: .normal)
            // 设置转发的微博的内容
            retweetedContentLab?.text = statusViewModel?.statusModel?.retweeted_status?.text
            // 外界给cell的视图模型赋值后，立刻计算pictureCollectionView的size，并更新
            let count = statusViewModel?.pictureArray?.count ?? 0
            let pictureViewSize = calculatePictureViewSize(count: count)
            pictureViewWidth.constant = pictureViewSize.width
            pictureViewHeight.constant = pictureViewSize.height
            pictureViewTopConstraint.constant = (count == 0 ? 0 : commonMargin)
            // 设置pictureCollectionView的layout
            if count == 1 {
                
                pictureViewFlowLayout.minimumLineSpacing = 0
                pictureViewFlowLayout.minimumInteritemSpacing = 0
                pictureViewFlowLayout.itemSize = pictureViewSize
            } else {
                
                pictureViewFlowLayout.minimumLineSpacing = pictureItemMargin
                pictureViewFlowLayout.minimumInteritemSpacing = pictureItemMargin
                pictureViewFlowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
            }
            // 给pictureCollectionView的数据源数组赋值
            pictureCollectionView.pic_urls = statusViewModel?.pictureArray
            /*
            pic_urls = statusViewModel?.pictureArray
            */
            
            
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        // Initialization code
//        backgroundColor = randomColor()
//        print(self.bounds)
        contentLab.preferredMaxLayoutWidth = UIScreen.main.bounds.width - 2 * commonMargin
        if retweetedContentLab != nil {
        retweetedContentLab?.preferredMaxLayoutWidth = UIScreen.main.bounds.width - 2 * commonMargin
//            print("转发微博awake")
        } else {
//            print("原创微博awake")
        }
        selectionStyle = .none
        /* 这部分设置pictureCollectionView的layout的代码放在此处不妥，因为cell复用时，此部分代码所在的awakeFromNib函数就不会被调用。
        // 设置pictureCollectionView的layout
        pictureViewFlowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        pictureViewFlowLayout.minimumLineSpacing = pictureItemMargin
        pictureViewFlowLayout.minimumInteritemSpacing = pictureItemMargin
        */
        /*
        pictureCollectionView.dataSource = self
        pictureCollectionView.delegate = self
        pictureCollectionView.register(WYJPictureCollectionViewCell.self, forCellWithReuseIdentifier: collectionViewCellID)
        */
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    private func calculatePictureViewSize(count: Int) -> CGSize {
        if count == 0 {
            return CGSize.zero
        }
        if count == 1 {
            let imageKey = statusViewModel?.pictureArray?.first?.wap_pic ?? ""
            let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: imageKey)
            return image!.size
        }
        if count == 4 {
            let width = 2 * itemWidth + pictureItemMargin
            return CGSize(width: width, height: width)
        }
        let rowCount = CGFloat((count - 1) / 3 + 1)
        let height = rowCount * itemWidth + (rowCount - 1) * pictureItemMargin
        
        return CGSize(width: maxWidth, height: height)
    }
    /*
    //~~pictureCollectionView的数据源协议方法~~~
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pic_urls?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellID, for: indexPath) as! WYJPictureCollectionViewCell
        //        cell.backgroundColor = randomColor()
        cell.pic_url = pic_urls?[indexPath.item]
        
        return cell
    }
}
    // MARK: 自定义collectionViewCell
    class WYJPictureCollectionViewCell: UICollectionViewCell {
        // 属性
        lazy var pictureImgV: UIImageView = {
            let imgV = UIImageView()
            imgV.contentMode = .scaleAspectFill
            imgV.clipsToBounds = true
            return imgV
        }()
        var pic_url: WYJStatusPictureModel? {
            didSet {
                let urlString = pic_url?.thumbnail_pic
//                print(urlString)
//                print("~~~~~~~~~~~~~~~~~~~~~~")
                let url = URL(string: urlString ?? "")
                pictureImgV.sd_setImage(with: url)
            }
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            contentView.addSubview(pictureImgV)
            pictureImgV.snp.makeConstraints { (make) in
                make.edges.equalTo(self)
            }
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
 */
}

